package com.jyu.apts.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.jyu.apts.dao.UserRepository;
import com.jyu.apts.dto.UserDto;
import com.jyu.apts.entity.Permission;
import com.jyu.apts.entity.Role;
import com.jyu.apts.entity.User;
import com.jyu.apts.entityEnum.UserStatusTypeEnum;

public class ShiroRealm extends AuthorizingRealm {

	Boolean cachingEnabled=true;
	
	@Autowired
	UserRepository userDao;
 
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
 
		SimpleAuthorizationInfo authorInfo = new SimpleAuthorizationInfo();
 
        String username = (String)principalCollection.getPrimaryPrincipal();
        
        User user = userDao.findByUsername(username);
        
        Set<String> roleSet = new HashSet<>();

        Set<String>  permissionSet = new HashSet<>();

    	Role role = user.getRole();
		roleSet.add(role.getStringRole());
		for(Permission perm : role.getPermissions()) {
			permissionSet.add(perm.getStringPermission());
		}
    	
    	authorInfo.setRoles(roleSet);
    	authorInfo.setStringPermissions(permissionSet);

		return authorInfo;
	}
 
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String username = token.getUsername();
		User user = userDao.findByUsername(username);
		if(user==null){throw new AuthenticationException("用户不存在");}
		if(user.getStatus()==UserStatusTypeEnum.unActive.getType()){throw new AuthenticationException("用户未激活");}
		AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),ByteSource.Util.bytes(user.getSalt()), getName());
		super.clearCachedAuthorizationInfo(authcInfo.getPrincipals());
		SecurityUtils.getSubject().getSession().setAttribute("userDto", new UserDto().convert(user));
		return authcInfo;
		
	}

}
